import { getUserInfo, setUserInfo, removeUserInfo, setToken, removeToken } from '@/utils/storage'
import { login } from '@/api/login'
import { Message } from 'element-ui'
import router from '@/router/index'
const state = {
  userInfo: JSON.parse(getUserInfo()),
  token: null
}
const mutations = {
  // 修改user
  saveUserInfo (state, payload) {
    state.userInfo = payload
    setUserInfo(payload)
  },
  saveToken (state, payload) {
    state.token = payload
    setToken(payload)
  }
}
const actions = {
  // 登录
  async login (context, payload) {
    const res = await login(payload)
    await context.commit('saveUserInfo', res)
    await context.commit('saveToken', res.token)
    Message(res.msg)
    router.push('/home')
  },
  // 退出
  logOut ({ commit }) {
    commit('userInfo', {})
    commit('saveToken', null)
    removeUserInfo()
    removeToken()
    router.push('/login')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
